<?php
namespace app\manage\controller;

use think\Controller;
use think\migration\command\migrate\Status;
use think\Request;
use think\Validate;
use think\Db;
use Config;
use app\common\model\TokenCheck;
use app\manage\model\OperationLog;
use app\manage\model\Role as m_Role;
use app\manage\model\RoleAction;
use app\manage\model\Action;

class Role extends Controller{
    public function __construct(Request $request = null)
    {
//        parent::__construct($request);
    }

    /**
     * 显示角色
     * @param   keyword         关键字
     * @param   p               页码
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function showRole() {
        $input = input();
        $keyword = isset($input['keyword']) ? trim($input['keyword']) : "";
        $page = isset($input['p']) ? trim($input['p']) : "";
        $create_id = isset($input['admin_id']) ? trim($input['admin_id']) : "";

        /**
         * 获取一页数据和总数，尚未进行错误判断与处理
         */
        $model=new m_Role();
        $create_id = $model->findPlatId($create_id);
        $onePage = $model->onePage($page, get_list_rows(), $keyword, $create_id);
        $total = $model->total($keyword, $create_id);

        $data['total'] = $total;
        $data['data'] = $onePage;
        returnJson(200,"成功", $data)->send();die;
    }

    /**
     * 增加角色
     * @param   name    角色名称
     * @param   is_platform    是否是平台管理员 1表示是 2表示否
     * @param   is_department    是否是部门管理员 1表示是 2表示否
     * @param   permission  权限，1,2,3
     */
    public function createRole() {
        $input = input();
        $validate = new Validate([
            ['name', 'require|max:50', '名称不能为空|不能超过20字'],
            ['is_platform', 'require', '是否是平台管理员不能为空'],
            ['is_department', 'require', '是否是部门管理员不能为空'],
        ]);
        if(!$validate->check($input))
        {
            returnJson(-1001,  $validate->getError())->send();die;
        }

        $data['name'] = isset($input['name']) ? trim($input['name']) : "";
        $data['is_platform'] = isset($input['is_platform']) ? trim($input['is_platform']) : "";
        $data['is_department'] = isset($input['is_department']) ? trim($input['is_department']) : "";
        $data['create_id'] = isset($input['admin_id']) ? trim($input['admin_id']) : "";
        $data['number'] = 0;
        $data['status'] = 1;
        $data['create_time'] = time();
        $data['update_time'] = time();

        $model=new m_Role();
        $data['create_id'] = $model->findPlatId($data['create_id']);
        // 验证唯一性
        if (($model->uniqueness($data['name'], $data['create_id']) !== 0)) {
            returnJson(-2012,"角色名已存在")->send();die;
        }

        $addtextRes=$model->m_insert($data);
        if (!$addtextRes) {
            returnJson(-2001,"服务器错误")->send();die;
        }

        // 插入角色权限表
        $data['permission'] = isset($input['permission']) ? trim($input['permission']) : "";
        if ($data['permission'] == '') {
            $all_permission = '';
        } else {
            $all_permission = $data['permission'];
            $all_permission = explode(',', $all_permission);
            $tmp = explode(',',$data['permission']);
            foreach ($tmp as $k =>$value) {
                if (intval($value) >= config('permission')['min'] && intval($value) <= config('permission')['max']) {
                    // 总权限操作
                    array_push($all_permission, $this->getParentNode($value));

                    // 底层权限操作
                } else {
                    // 总权限操作

                    // 底层权限操作
                    unset($tmp[$k]);
                }
            }
            $all_permission = implode(',', array_unique($all_permission));
            $data['permission'] = implode(',', $tmp);
        }

        $model = new RoleAction();
        $actions = $model->setActionRelation($addtextRes, $data['permission'], $all_permission);
        if ($actions) {
            returnJson(200,"成功", $addtextRes)->send();die;
        } else {
            returnJson(-2001,"服务器错误")->send();die;
        }
    }

    /**
     * 获取所有权限
     */
    public function getAllAction() {
        $model = new Action();
        $actions = $model->m_list();

        if (get_user_id(input()['token']) != 1) {
            unset($actions[0]['children_list'][0]);
        }
        $actions[0]['children_list'] = array_merge_recursive($actions[0]['children_list']);
        returnJson(200,"成功", ($actions))->send();die;
    }

    /**
     * 根据角色获取权限
     * @param $role_id
     */
    public function getAction() {
        $input = input();
        $role_id = $input['role_id'];
        $model = new RoleAction();
        $data = $model->detail($role_id);//获取角色对应的权限id
        $data = explode(',', $data['action_id']);

//        $model = new Action();
//        $detail= $model->detail($data);
        returnJson(200,"成功", $data)->send();die;
    }

    /**
     * 更新角色账户
     * @param   role_id
     * @param   name    角色名称
     * @param   is_platform    是否是平台管理员 1表示是 2表示否
     * @param   is_department    是否是部门管理员 1表示是 2表示否
     * @param   permission  权限，1,2,3
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function editRole() {
        $input = input();
        $validate = new Validate([
            ['role_id', 'require', '角色id不能为空'],
            ['name', 'require|max:50', '名称不能为空|不能超过20字'],
            ['is_platform', 'require', '是否是平台管理员不能为空'],
            ['is_department', 'require', '是否是部门管理员不能为空'],
        ]);
        if(!$validate->check($input))
        {
            returnJson(-1001,  $validate->getError())->send();die;
        }

        $role_id = isset($input['role_id']) ? trim($input['role_id']) : "";
        $data['name'] = isset($input['name']) ? trim($input['name']) : "";
        $data['is_platform'] = isset($input['is_platform']) ? trim($input['is_platform']) : "";
        $data['is_department'] = isset($input['is_department']) ? trim($input['is_department']) : "";
        $permission = isset($input['permission']) ? trim($input['permission']) : "";
        $data['update_time'] = time();

        if ($permission == '') {
            $all_permission = '';
        } else {
            $all_permission = $permission;
            $all_permission = explode(',',$all_permission);
            $tmp = explode(',',$permission);
            foreach ($tmp as $k =>$value) {
                if (intval($value) >= config('permission')['min'] && intval($value) <= config('permission')['max']) {
                    // 总权限操作
                    array_push($all_permission, $this->getParentNode($value));

                    // 底层权限操作
                } else {
                    // 总权限操作

                    // 底层权限操作
                    unset($tmp[$k]);
                }
            }
            $all_permission = implode(',', array_unique($all_permission));
            $permission = implode(',', $tmp);
        }


        $model=new m_Role();
        $edittextRes=$model->m_update($role_id, $data);
        if (!$edittextRes) {
            returnJson(-2013,"数据无变化")->send();die;
        }

        /**
         * 编辑角色权限关联表
         */
        $model = new RoleAction();
        $dataRoleAction['action_id'] = $permission;
        $edittextRes=$model->updateActionRelation($role_id, $dataRoleAction['action_id'], $all_permission);
        returnJson(200,"成功")->send();die;
//        if ($edittextRes) {
//            returnJson(200,"成功")->send();die;
//        } else {
//            returnJson(-2013,"数据无变化")->send();die;
//        }
    }

    /**
     * @param   role_id
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function deleteRole() {
        $input = input();
        $validate = new Validate([
            ['role_id', 'require', '平台id不能为空']
        ]);
        if(!$validate->check($input))
        {
            returnJson(-1001,  $validate->getError())->send();die;
        }

        $role_id = isset($input['role_id']) ? trim($input['role_id']) : "";

        /**
         * 查看是否有隶属于该角色的用户
         */
        $model=new m_Role();
        $count = $model->detail($role_id);
        if ($count['number'] !== 0) {
            returnJson(-2001,"存在属于该角色的用户，请先删除")->send();die;
        }

        $data['status'] = 3;
        $deletetextRes=$model->m_update($role_id, $data);
        if ($deletetextRes) {
            returnJson(200,"成功")->send();die;
        } else {
            returnJson(-2013,"数据无变化")->send();die;
        }
    }

    /**
     * @param   role_id
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function detailRole() {
        $input = input();
        $validate = new Validate([
            ['role_id', 'require', '平台id不能为空']
        ]);
        if(!$validate->check($input))
        {
            returnJson(-1001,  $validate->getError())->send();die;
        }

        $role_id = isset($input['role_id']) ? trim($input['role_id']) : "";

        $model=new m_Role();
        $detailtextRes=$model->detail($role_id);
        if (!$detailtextRes) {
            returnJson(-2001,"服务器错误")->send();die;
        }

        $model = new RoleAction();
        $data = $model->getActionRelation($role_id);
        $detailtextRes['permission'] = $data['action_id'];
        returnJson(200,"成功", $detailtextRes)->send();die;
    }

    /**
     * 获取父节点id
     * @param $role_id
     * @return mixed|string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function getParentNode($role_id) {
        $model = new Action();
        $data = $model->detailOne($role_id);
        if (isset($data['pid'])) {
            return $data['pid'];
        } else {
            return '';
        }
    }

}